package sms

import (
	"bytes"
	"context"
	"github.com/google/wire"
	"github.com/uber/tchannel-go/thrift"
	api "go.didapinche.com/goapi/plat_sms_service_api"
	"go.uber.org/zap"
	"strings"
	"text/template"
	"time"
)

const (
	serviceName = "com.didapinche.thrift.api.SMSService"
	productID   = 17 // 腾讯云
)

type SmsService struct {
	client api.TChanSMSService
	logger *zap.Logger
}

func NewSmsService(logger *zap.Logger, client api.TChanSMSService) (*SmsService, error) {

	return &SmsService{
		client: client,
		logger: logger,
	}, nil
}

// Send 发送短信
func (s *SmsService) Send(ctx context.Context, to []string, temp string, args interface{}) {
	var (
		t      *template.Template
		err    error
		buffer bytes.Buffer
	)
	if t, err = template.New("sms").Parse(temp); err != nil {
		s.logger.Error("send sms parse temp err", zap.Error(err))
		return
	}
	// 解析模板
	if err = t.Execute(&buffer, args); err != nil {
		s.logger.Error("send sms execute temp err", zap.Error(err))
		return
	}
	ctx2, _ := context.WithTimeout(ctx, 3*time.Second)
	if err = s.client.BatchSend(thrift.Wrap(ctx2), productID, strings.Join(to, ","), buffer.String()); err != nil {
		s.logger.Error("send sms error", zap.Error(err))
		return
	}
}

var ProviderSet = wire.NewSet(NewSmsService)
